//
//  FWLogger.m
//  iOSToolkit
//
//  Created by Evan Xie on 8/27/15.
//  Copyright (c) 2015 Family Wings. All rights reserved.
//

#import <pthread/pthread.h>
#import "FWLogger.h"


@interface FWLogger ()
{
    NSMutableString *_logBuffer;
    
    pthread_mutex_t _mutex;
}

@end

@implementation FWLogger

+ (instancetype)sharedLogger
{
    static FWLogger *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [FWLogger new];
    });
    return instance;
}

- (instancetype)init
{
    if (self = [super init]) {
        _logBuffer = [NSMutableString stringWithCapacity:0];
        
        pthread_mutex_init(&_mutex, NULL);
    }
    return self;
}

- (void)dealloc
{
    pthread_mutex_destroy(&_mutex);
}

- (NSString *)logMessagesInMemory
{
    return [_logBuffer copy];
}

- (void)logMessage:(NSString *)logMessage
{
    pthread_mutex_lock(&_mutex);
    [_logBuffer appendFormat:@"%@\n\r", logMessage];
    pthread_mutex_unlock(&_mutex);
}

- (void)logMessageWithFromat:(NSString *)format, ...
{
    pthread_mutex_lock(&_mutex);
    
    va_list arg_list;
    va_start(arg_list, format);
    NSString *message = [[NSString alloc] initWithFormat:format arguments:arg_list];
    [_logBuffer appendFormat:@"%@\n\r", message];
    va_end(arg_list);
    pthread_mutex_unlock(&_mutex);
}

- (void)clearLog
{
    pthread_mutex_lock(&_mutex);
    [_logBuffer setString:@""];
    pthread_mutex_unlock(&_mutex);
}

@end
